package com.foreknow.elm.service.impl;

import com.foreknow.elm.dao.CartDao;
import com.foreknow.elm.dao.OrderdetailetDao;
import com.foreknow.elm.dao.impl.CartDaoImpl;
import com.foreknow.elm.dao.impl.OrderdetailetDaoImpl;
import com.foreknow.elm.dao.impl.OrdersDaoImpl;
import com.foreknow.elm.po.Cart;
import com.foreknow.elm.po.Orderdetailet;
import com.foreknow.elm.po.Orders;
import com.foreknow.elm.service.OrdersService;
import com.foreknow.elm.util.DBUtil;
import com.sun.org.apache.xpath.internal.operations.Or;
import sun.security.pkcs11.Secmod;

import java.util.ArrayList;
import java.util.List;

public class OrdersServiceImpl implements OrdersService {
    @Override
    public int createOrders(Orders orders) {
        int orderId = 0;
            OrdersDaoImpl dao = new OrdersDaoImpl();
            CartDao cartService=new CartDaoImpl();
            try {
                DBUtil.beginTransaction();
                orderId = dao.createOrders(orders);
                List<Cart> list = cartService.listCart(orders.getUserId(), orders.getBusinessId());
                Orderdetailet orderdetailet = new Orderdetailet();
                List<Orderdetailet> orderdetailets = new ArrayList<>();
                for (Cart cart : list) {
                    orderdetailet.setOrderId(orderId);
                    orderdetailet.setFoodId(cart.getFoodId());
                    orderdetailet.setQuantity(cart.getQuantity());
                    orderdetailets.add(orderdetailet);
                }
                OrderdetailetDao orderdetailetService = new OrderdetailetDaoImpl();
                orderdetailetService.save(orderdetailets);
                cartService.removeCart(orders.getUserId(),orders.getBusinessId());
                DBUtil.commitTransaction();
            } catch (Exception e) {
                e.printStackTrace();
                try {
                    DBUtil.rollbackTransaction();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }finally {
                DBUtil.close();
            }
        return orderId;
    }

    @Override
    public Orders getOrdersById(Integer orderId) {
        Orders orders = new Orders();
        OrdersDaoImpl ordersService = new OrdersDaoImpl();
        try {
            DBUtil.beginTransaction();
            orders = ordersService.getOrdersById(orderId);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            DBUtil.close();
        }
        return orders;
    }

    @Override
    public List<Orders> listOrdersByUserId(String userId) {
        List<Orders> orders = new ArrayList<>();
        OrdersDaoImpl dao = new OrdersDaoImpl();
        try {
            DBUtil.getConnection();
            orders = dao.listOrdersByUserId(userId);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            DBUtil.close();
        }
        return orders;
    }

}
